const WXAPI = require('apifm-wxapi')
const app = getApp();
const SETGOODS = require('../../utils/setgoos.js');
Page({
  data: {
    // goodsList: {
    //   saveHidden: true,
    //   totalPrice: 0,
    //   totalScoreToPay: 0,
    //   allSelect: true,
    //   noSelect: false,
    //   list: []
    // },
    goodsList:{
      list: [],
      listNo:0,
      checked: true,
      totalPrice: 0,
      option: [
        { text: '全部商品', value: 0 },
        { text: '新款商品', value: 1 },
        { text: '活动商品', value: 2 }
      ],
      value: 0,
      allSelect: false,
    },
    delBtnWidth: 120, //删除按钮宽度单位（rpx）
  },


  //获取元素自适应后的实际宽度
  getEleWidth: function(w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },
  initEleWidth: function() {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  onLoad: function() {
    this.initEleWidth();
    // this.onShow();
    // 屏蔽分享
    wx.hideShareMenu();
  },
  onShow: function() {
    let that = this;
    var shopList = [];
    // 获取购物车数据
    var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
    console.log(shopCarInfoMem)
    if (shopCarInfoMem && shopCarInfoMem.length > 0) {
      shopList = shopCarInfoMem
    }
    
    // this.data.goodsList.list = shopList;
    this.data.goodsList.list = shopCarInfoMem;
    this.getLength(shopCarInfoMem);
    // this.allSelect();

    // 判断商店内都选中
    this.checkShopAllChecked();
    // 判断所有商店都选中
    this.checkAllChecked();
    this.totalPrice();

    // this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), shopList);
  },
  getLength(list){
    let no = 0;
    for (let listItem of list){
      no += listItem.list.length;
    }
    
    let goodsList = this.data.goodsList;
    goodsList.listNo = no;
    app.globalData.goodsNo = no;
    this.setData({
      goodsList: goodsList,
    })
  },

  toIndexPage: function() {
    wx.switchTab({
      url: "/pages/index/index"
    });
  },

  // touchS: function(e) {
  //   if (e.touches.length == 1) {
  //     this.setData({
  //       startX: e.touches[0].clientX
  //     });
  //   }
  // },
  // touchM: function(e) {
  //   var index = e.currentTarget.dataset.index;

  //   if (e.touches.length == 1) {
  //     var moveX = e.touches[0].clientX;
  //     var disX = this.data.startX - moveX;
  //     var delBtnWidth = this.data.delBtnWidth;
  //     var left = "";
  //     if (disX == 0 || disX < 0) { //如果移动距离小于等于0，container位置不变
  //       left = "margin-left:0px";
  //     } else if (disX > 0) { //移动距离大于0，container left值等于手指移动距离
  //       left = "margin-left:-" + disX + "px";
  //       if (disX >= delBtnWidth) {
  //         left = "left:-" + delBtnWidth + "px";
  //       }
  //     }
  //     var list = this.data.goodsList.list;
  //     if (index != "" && index != null) {
  //       list[parseInt(index)].left = left;
  //       this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  //     }
  //   }
  // },

  // touchE: function(e) {
  //   var index = e.currentTarget.dataset.index;
  //   if (e.changedTouches.length == 1) {
  //     var endX = e.changedTouches[0].clientX;
  //     var disX = this.data.startX - endX;
  //     var delBtnWidth = this.data.delBtnWidth;
  //     //如果距离小于删除按钮的1/2，不显示删除按钮
  //     var left = disX > delBtnWidth / 2 ? "margin-left:-" + delBtnWidth + "px" : "margin-left:0px";
  //     var list = this.data.goodsList.list;
  //     if (index !== "" && index != null) {
  //       list[parseInt(index)].left = left;
  //       this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);

  //     }
  //   }
  // },

  // 获取选中商品价格
  totalPrice: function() {
    var list = this.data.goodsList.list;
    var total = 0;
    // let totalScoreToPay = 0;
    for (let item of list){
      for (let itemList of item.list){
        if (itemList.checked){
          total += parseFloat(itemList.price) * itemList.buyNumber;
        }
      }
    }
    total = parseFloat(total.toFixed(2));
    
    let goodsList = this.data.goodsList;
    goodsList.totalPrice = total;
    this.setData({
      goodsList: goodsList
    })
    // for (var i = 0; i < list.length; i++) {
    //   var curItem = list[i];
    //   if (curItem.active) {
    //     total += parseFloat(curItem.price) * curItem.number;
    //     totalScoreToPay += curItem.score * curItem.number;
    //   }
    // }
    // this.data.goodsList.totalScoreToPay = totalScoreToPay;
    // total = parseFloat(total.toFixed(2)); //js浮点计算bug，取两位小数精度
    // console.log(total)
    // return total;
  },
  // 删除当前商品
  onClose(e) {
    let that = this;
    let stockNo = e.currentTarget.dataset.stockno;
    let shopNo = e.currentTarget.dataset.shopno;
    console.log(e)
    const { position, instance } = e.detail;
    switch (position) {
      case 'left':
      case 'cell':
        instance.close();
        break;
      case 'right':
        wx.showModal({
          title: '提示',
          content: '确定删除吗？',
          success(e){
            console.log(stockNo)
            if (e.confirm){
              that.delGood(shopNo, stockNo);
            }
            instance.close();
          },
          fail(){
            instance.close();
          }
        })
        break;
    }
  },
  // 删除商品
  delGood(shopNo, stockNo){
    let list = this.data.goodsList.list;
    for (let [ind, listItem] of list.entries()){
      if (listItem.shopNo == shopNo){
        for (let [index, goodItem] of listItem.list.entries()) {
          if (goodItem.stockNo == stockNo) {
            listItem.list.splice(index, 1);
            if (listItem.list.length == 0) {
              list.splice(ind, 1);
            }
          }
        }
      }
    }
    
    // 判断商店内都选中
    this.checkShopAllChecked();
    // 判断所有商店都选中
    this.checkAllChecked();

    this.totalPrice();
    this.setLocal();
    app.getGoodsNo();
    this.getLength(list);
  },
  // 勾选商店
  onChangeShop(e){
    let shopNo = e.currentTarget.dataset.shopno;
    let list = this.data.goodsList.list;
    for (let listItem of list){
      if (listItem.shopNo == shopNo){
        if (listItem.checked){
          listItem.checked = false;
          for (let goodItem of listItem.list) {
            goodItem.checked = false;
          }
        }else{
          listItem.checked = true;
          for (let goodItem of listItem.list){
            goodItem.checked = true;
          }
        }
      }
    }
    // 判断所有商店都选中
    this.checkAllChecked();

    this.totalPrice();
    this.setLocal();
  },
  // 判断全选
  checkAllChecked(){
    let list = this.data.goodsList.list;
    let goodsList = this.data.goodsList;
    let ind = 0;
    // 处理，判断全选
      for (let listItem of list) {
        listItem.list.filter((val, index) => {
          if (val.checked) {
            ind++;
            if (listItem.list.length == ind) {
              goodsList.allSelect = true;
            }else{
              goodsList.allSelect = false;
            }
          }else{
            goodsList.allSelect = false;
          }
        })
      }
    // }
    this.setData({
      goodsList: goodsList
    })
  },

  // 判断商店内全选
  checkShopAllChecked(){
    let list = this.data.goodsList.list;
    let ind = 0;
    // 处理，判断商店内所有已选中

    for (let listItem of list) {
      if (listItem.list.length > 1){
        listItem.list.filter((val, index) => {
          if (val.checked) {
            listItem.checked = false;
            ind++;
            if (listItem.list.length == ind) {
              listItem.checked = true;
            }
          }
        })
      }else{
        listItem.checked = listItem.list[0].checked;
      }
      
      // listItem.chekedNo = ind;
    }
    // console.log(list)
  },
  // 勾选商品
  onChangeGood(e){
    let stockNo = e.currentTarget.dataset.stockno;
    let shopNo = e.currentTarget.dataset.shopno;
    console.log(stockNo)
    console.log(shopNo)
    let list = this.data.goodsList.list;
    for (let listItem of list) {
      if (listItem.shopNo == shopNo) {
        for (let goodItem of listItem.list) {
          if (goodItem.stockNo == stockNo){
            if (goodItem.checked) {
              goodItem.checked = false;
            } else {
              goodItem.checked = true;
            }
          }
        }
      }
    }

    // 判断商店内都选中
    this.checkShopAllChecked();
    // 判断所有商店都选中
    this.checkAllChecked();

    this.totalPrice();
    this.setLocal();

  },

  allSelect: function() {
    // var list = this.data.goodsList.list;
    // var allSelect = false;
    // for (var i = 0; i < list.length; i++) {
    //   var curItem = list[i];
    //   if (curItem.active) {
    //     allSelect = true;
    //   } else {
    //     allSelect = false;
    //     break;
    //   }
    // }
    // return allSelect;

  },
  // 判断有选中
  noSelect: function() {
    let list = this.data.goodsList.list;
    let noSelect = false;
    for (let listItem of list) {
      listItem.list.filter((val, index) => {
        if (val.checked) {
          noSelect = true;
        }
      })
    }
    return noSelect;
  },
  setGoodsList: function(saveHidden, total, allSelect, noSelect, list) {
    var shopCarInfo = {};
    var tempNumber = 0;
    shopCarInfo.shopList = list;
    for (var i = 0; i < list.length; i++) {
      tempNumber = tempNumber + list[i].number
    }
    shopCarInfo.shopNum = tempNumber;
    // wx.setStorage({
    //   key: "shopCarInfo",
    //   data: shopCarInfo
    // })
  },
  // 所有全选
  bindAllSelect: function() {
    let list = this.data.goodsList.list;
    for (let listItem of list) {
      if (listItem.checked) {
        listItem.checked = false;
        // noSelect
        for (let goodItem of listItem.list) {
          goodItem.checked = false;
        }
      } else {
        listItem.checked = true;
        for (let goodItem of listItem.list) {
          goodItem.checked = true;
        }
      }
    }

    // 判断所有商店都选中
    this.checkAllChecked();

    this.totalPrice();
    this.setLocal();

  },
  jiaBtnTap: function(e) {
    let shopNo = e.currentTarget.dataset.shopno;
    let stockNo = e.currentTarget.dataset.stockno;
    let value = e.currentTarget.dataset.val;
    let list = this.data.goodsList.list;
    for (let itemList of list) {
      if (shopNo == itemList.shopNo) {
        for (let goodItem of itemList.list) {
          if (goodItem.stockNo == stockNo) {
            goodItem.buyNumber++;
            goodItem.buyMoney = parseFloat(goodItem.price) * (goodItem.buyNumber);
          }
        }
      }
    }
    this.totalPrice();
    this.setLocal();
  },
  // 减少数量
  jianBtnTap: function(e) {
    let shopNo = e.currentTarget.dataset.shopno;
    let stockNo = e.currentTarget.dataset.stockno;
    let value = e.currentTarget.dataset.val;
    let list = this.data.goodsList.list;
    for(let itemList of list){
      if (shopNo == itemList.shopNo){
        for (let goodItem of itemList.list){
          if (goodItem.stockNo == stockNo ){
            if (goodItem.buyNumber > 1){
              goodItem.buyNumber--;
              goodItem.buyMoney = parseFloat(goodItem.price) * (goodItem.buyNumber);
            }
          }
        }
      }
    }
    this.totalPrice();
    this.setLocal();
  },

  // 处理过的数据，放入缓存
  setLocal(){
    let that = this;
    let goodsList = this.data.goodsList;
    if (goodsList.list.length > 0){
      wx.setStorage({
        key: 'shopCarInfo',
        data: goodsList.list,
      })
    }else{
      goodsList.allSelect = false;
      that.setData({
        goodsList: goodsList
      })
      wx.removeStorage({ key: 'shopCarInfo' })
    }
    
  },
  editTap: function() {
    // var list = this.data.goodsList.list;
    // for (var i = 0; i < list.length; i++) {
    //   var curItem = list[i];
    //   curItem.active = false;
    // }
    // this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  saveTap: function() {
    // var list = this.data.goodsList.list;
    // for (var i = 0; i < list.length; i++) {
    //   var curItem = list[i];
    //   curItem.active = true;
    // }
    // this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  getSaveHide: function() {
    // var saveHidden = this.data.goodsList.saveHidden;
    // return saveHidden;
  },
  deleteSelected: function() {
    var list = this.data.goodsList.list;
    /*
     for(let i = 0 ; i < list.length ; i++){
           let curItem = list[i];
           if(curItem.active){
             list.splice(i,1);
           }
     }
     */
    // above codes that remove elements in a for statement may change the length of list dynamically
    list = list.filter(function(curGoods) {
      return !curGoods.active;
    });
    this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  toPayOrder: function() {
    let that = this;
    if (that.noSelect()){
      // 先校验有token
      wx.getStorage({
        key: 'token',
        success: function (res) {
          console.log(res);
          if (res.data && res.data != '') {

            SETGOODS.setBuyNowGoods(that.data.goodsList.list);
            that.navigateToPayOrder();
          } else {
            app.showLoadText('请先登录','my');
            
          }
        },
        fail() {
          app.showLoadText('请先登录', 'my');
        }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '请选择要支付的商品',
        showCancel: false
      })
    }
    



    // wx.showLoading();
    // var that = this;
    // if (this.data.goodsList.noSelect) {
    //   wx.hideLoading();
    //   return;
    // }
    // // 重新计算价格，判断库存
    // var shopList = [];
    // var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
    // if (shopCarInfoMem && shopCarInfoMem.shopList) {
    //   // shopList = shopCarInfoMem.shopList
    //   shopList = shopCarInfoMem.shopList.filter(entity => {
    //     return entity.active;
    //   });
    // }
    // if (shopList.length == 0) {
    //   wx.hideLoading();
    //   return;
    // }
    // var isFail = false;
    // var doneNumber = 0;
    // var needDoneNUmber = shopList.length;
    // for (let i = 0; i < shopList.length; i++) {
    //   if (isFail) {
    //     wx.hideLoading();
    //     return;
    //   }
    //   let carShopBean = shopList[i];
    //   // 获取价格和库存
    //   if (!carShopBean.propertyChildIds || carShopBean.propertyChildIds == "") {
    //     WXAPI.goodsDetail(carShopBean.goodsId).then(function(res) {
    //       doneNumber++;
    //       if (res.data.properties) {
    //         wx.showModal({
    //           title: '提示',
    //           content: res.data.basicInfo.name + ' 商品已失效，请重新购买',
    //           showCancel: false
    //         })
    //         isFail = true;
    //         wx.hideLoading();
    //         return;
    //       }
    //       if (res.data.stockNum < carShopBean.number) {
    //         wx.showModal({
    //           title: '提示',
    //           content: res.data.basicInfo.name + ' 库存不足，请重新购买',
    //           showCancel: false
    //         })
    //         isFail = true;
    //         wx.hideLoading();
    //         return;
    //       }
    //       if (res.data.price != carShopBean.price) {
    //         wx.showModal({
    //           title: '提示',
    //           content: res.data.basicInfo.name + ' 价格有调整，请重新购买',
    //           showCancel: false
    //         })
    //         isFail = true;
    //         wx.hideLoading();
    //         return;
    //       }
    //       if (needDoneNUmber == doneNumber) {
    //         that.navigateToPayOrder();
    //       }
    //     })
    //   } else {
    //     WXAPI.goodsPrice({
    //       goodsId: carShopBean.goodsId,
    //       propertyChildIds: carShopBean.propertyChildIds
    //     }).then(function(res) {
    //       doneNumber++;
    //       if (res.data.stores < carShopBean.number) {
    //         wx.showModal({
    //           title: '提示',
    //           content: carShopBean.name + ' 库存不足，请重新购买',
    //           showCancel: false
    //         })
    //         isFail = true;
    //         wx.hideLoading();
    //         return;
    //       }
    //       if (res.data.price != carShopBean.price) {
    //         wx.showModal({
    //           title: '提示',
    //           content: carShopBean.name + ' 价格有调整，请重新购买',
    //           showCancel: false
    //         })
    //         isFail = true;
    //         wx.hideLoading();
    //         return;
    //       }
    //       if (needDoneNUmber == doneNumber) {
    //         that.navigateToPayOrder();
    //       }
    //     })
    //   }

    // }
  },
  navigateToPayOrder: function() {
    wx.hideLoading();
    wx.navigateTo({
      url: "/pages/to-pay-order/index"
    })
  }



})